<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use OSS\Core\OssException;
use OSS\OssClient;
use think\facade\Cache;
use think\facade\Db;
use think\facade\View;
use think\Request;
use think\Response;

class Article extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return View::fetch();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $redis = Cache::store('redis');
        $json = $redis->get('type');
        $type = json_decode($json, true);
        View::assign('types', $type);
        return View::fetch();
    }

    public function articles(Request $request)
    {
        $limit = input('limit');
        $key = input('key');
        if ($key == '') {
            $data = \app\admin\model\Article::paginate($limit)->toArray();
        } else {
            $data = \app\admin\model\Article::where('topic', 'like', "%$key%")->paginate($limit)->toArray();
        }
        return json(['code' => 0, 'count' => $data['total'], 'data' => $data['data']]);
    }


    public function Oss(Request $request)
    {
        $path = $request->file('file')->getPathname();
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        $accessKeyId = "LTAI4G3N1S4pMrVNx77dSA7v";
        $accessKeySecret = "w2WPCRxM1xnL7q9XZDyd9zGM3w1nKf";
// Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = "http://oss-cn-shanghai.aliyuncs.com";
// 设置存储空间名称。
        $bucket = "bliuce";
// 设置文件名称。
        $object = time() . ".jpg";
// <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
        $filePath = $path;

        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            $ossClient->uploadFile($bucket, $object, $filePath);
        } catch (OssException $e) {
            if ($e->getHTTPStatus() == 502 || $e->getErrorCode() == 400) {
                return json(['code' => 300, 'msg' => '网络无连接，请稍后重试', 'data' => '']);
            } else {
                return json(['code' => 300, 'msg' => '未知错误', 'data' => '']);
            }
        }
        $url = $this->getUrl($object);
        return json(['code' => 200, 'msg' => '上传成功', 'url' => $url]);
    }

    public function getUrl($obj)
    {
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        $accessKeyId = "LTAI4G3N1S4pMrVNx77dSA7v";
        $accessKeySecret = "w2WPCRxM1xnL7q9XZDyd9zGM3w1nKf";
// Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = "https://oss-cn-shanghai.aliyuncs.com";
        $bucket = "bliuce";
        $object = $obj;

        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

// 生成一个带图片处理参数的签名的URL，有效期是3600秒，可以直接使用浏览器访问。
        $timeout = 3600 * 5;
        $options = array(
            OssClient::OSS_PROCESS => "image/resize,m_lfit,h_100,w_100");
        $signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
        return $signedUrl;
    }


    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $params = $request->param();
        unset($params['file']);
        try {
            $this->validate($params, [
                'topic' => 'require',
                'pic' => 'require'
            ]);
        } catch (\Exception $e) {
            return json(['code' => 300, 'msg' => '标题或图片不能为空', 'data' => '']);
        }
        $params['add_time'] = time();
        try {
            $flag = \app\admin\model\Article::create($params);
        } catch (\Exception $e) {
            if ($e->getCode() == 10501) {
                return json(['code' => 300, 'msg' => '标题名重复，请重新填写', 'data' => '']);
            }
        }
        if ($flag) {
            return json(['code' => 200, 'msg' => '添加成功', 'data' => '']);
        } else {
            return json(['code' => 200, 'msg' => '添加失败', 'data' => '']);
        }
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit(Request $request)
    {
        $redis = Cache::store('redis');
        $json = $redis->get('type');
        $type = json_decode($json, true);
        View::assign('types', $type);
        $id = input('id');
        $data = \app\admin\model\Article::find($id)->toArray();
        View::assign('data', $data);
        return View::fetch();
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request)
    {
        $params = $request->param();
        try {
            $this->validate($params, [
                'topic' => 'require',
                'pic' => 'require',
                'view' => 'require',
                'comment_num' => 'require',
            ]);
        } catch (\Exception $e) {
            return json(['code' => 300, 'msg' => '选填项不能为空', 'data' => '']);
        }
        $id = $params['id'];
        unset($params['file']);
        unset($params['id']);
        try {
            $flag = \app\admin\model\Article::where('id', $id)->update($params);
        } catch (\Exception $e) {
            if ($e->getCode() == 10501) {
                return json(['code' => 300, 'msg' => '标题名重复，请重新填写', 'data' => '']);
            }
        }
        if ($flag) {
            return json(['code' => 200, 'msg' => '更新成功', 'data' => '']);
        } else {
            return json(['code' => 300, 'msg' => '更新失败', 'data' => '']);
        }
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    public function delAll(Request $request)
    {
        $params = $request->param();
        $ids = $params['ids'];
        $ids = rtrim($ids, ",");
        $arr = explode(",", $ids);
        try {
            foreach ($arr as $value) {
                \app\admin\model\Article::destroy($value);
            }
        } catch (\Exception $e) {
            return json(['code' => 300, 'msg' => '批量删除失败', 'data' => '']);
        }
        return json(['code' => 200, 'msg' => '批量删除成功', 'data' => '']);
    }
}
